from django.shortcuts import render,HttpResponse,redirect,reverse
from django.contrib.auth.decorators import login_required
from .base import *
from django.http import JsonResponse
from home.models import *
import json
import os
from teachzero.user_settings import *
from home.views import user_check
def getRootPath():
    
    return MEDIA_ROOT
# Create your views here.
@login_required
def filemanage(request):
    user_instance = user_check(request)
    if user_instance:
        print("user_instance:",user_instance)
        if user_instance["superuser"]:
            #将filemanage设置到appModel里
            #addFileMangeToAppModel()

            print("base user:",user_instance)
            print("main_view")
            tempMediaRoot=getRootPath()
            fileList=generate_znodes(tempMediaRoot)
            print("fileList:", fileList)
            return render(request, 'filemanage.html',{"fileList":fileList,"user":user_instance})
        else:
            return render(request, "home/index.html")
            #return render(request, 'mainLogin.html')
    else:
        return render(request, "home/index.html")
        #return render(request, 'mainLogin.html')
@login_required
def deleteFile(request):
    print("deleteFile")
    user_instance = user_check(request)
    if user_instance:
        #判断是否为post
        if request.method == "POST":
            content_type = request.content_type
            if content_type == 'application/x-www-form-urlencoded' or content_type == 'multipart/form-data':
                data = request.POST.get('data')
            else:
                data = json.loads(request.body)

            print("data:", data)
            #data = request.POST.get('data')
            #data = json.loads(request.body)
            #print("data:", data.fromNodeId, data.toNodeId)
            path = data.get('path')
            name = data.get('name')
            #path="123"
            #name="456"
            print("path:", path, "name:", name)

            tempMediaRoot=getRootPath()
            deleteResult=deleteFile(tempMediaRoot, path, name)
            print("deleteResult:", deleteResult)
            if deleteResult:
                return JsonResponse({"status":200, "message":"ok", "data":deleteResult})
            else:
                return JsonResponse({"status":400, "message":"error"})
    else:
        return render(request, 'mainLogin.html')
@login_required
#修改文件名
def renameFile(request):
    print("renameFile")
    user_instance = user_check(request)
    if user_instance:
        #判断是否为post
        if request.method == "POST":
            content_type = request.content_type
            if content_type == 'application/x-www-form-urlencoded' or content_type == 'multipart/form-data':
                data = request.POST.get('data')
            else:
                data = json.loads(request.body)

            print("data:", data)
            #data = request.POST.get('data')
            #data = json.loads(request.body)
            #print("data:", data.fromNodeId, data.toNodeId)
            path = data.get('path')
            name = data.get('name')
            newName = data.get('newName')
            #path="123"
            #name="456"
            print("path:", path, "name:", name)

            tempMediaRoot=getRootPath()
            renameResult=renameFile(tempMediaRoot, path, name,newName)
            print("renameResult:", renameResult)
            if renameResult:
                return JsonResponse({"status":200, "message":"ok", "data":{"name":renameResult["name"], "path":renameResult["path"]}})
            else:
                return JsonResponse({"status":400, "message":"error"})
        else:
            return JsonResponse({"status":400, "message":"error"})
    else:
        return render(request, 'mainLogin.html')
@login_required
#添加文件夹
def addFolder(request):
    print("addFolder")
    user_instance = user_check(request)
    if user_instance:
        #判断是否为post
        if request.method == "POST":
            content_type = request.content_type
            print("content_type:",content_type)
            if content_type == 'application/x-www-form-urlencoded' or content_type == 'multipart/form-data':
                data = request.POST.get('data')
            else:
                data = json.loads(request.body)

            print("data:", data)
            #data = request.POST.get('data')
            #data = json.loads(request.body)
            #print("data:",data.fromNodeId,data.toNodeId)
            path = data.get('path')
            name = data.get('name')
            folder_type=data.get('folder_type')
            #folder_content=data.get('folder_content')
            #path="123"
            #name="456"
            print("path:", path,"name:", name,"folder_type:",folder_type)
            tempMediaRoot=getRootPath()
            if path:
                addResult=addFolder(tempMediaRoot,path,name,folder_type)
            else:
                addResult=addFolder(tempMediaRoot,None,name,folder_type)
            print("addResult:", addResult)
            if addResult:
                return JsonResponse({"status":200,"message":"ok","data":{"name":addResult["name"],"path":addResult["path"]}})
            else:
                return JsonResponse({"status":400, "message":"error", "data":{}})
    else:
        return render(request, 'mainLogin.html')
@login_required
#更新文件
def updateFile(request):
    print("updateFile")
    user_instance = user_check(request)
    if user_instance:
        #判断是否为post
        if request.method == "POST":
            content_type = request.content_type
            if content_type == 'application/x-www-form-urlencoded' or content_type == 'multipart/form-data':
                data = request.POST.get('data')
            else:
                data = json.loads(request.body)

            print("data:", data)
            #data = request.POST.get('data')
            #data = json.loads(request.body)
            #print("data:", data.fromNodeId, data.toNodeId)
            path = data.get('path')
            name = data.get('name')
            content=data.get('content')
            #path="123"
            #name="456"
            print("path:", path, "name:", name,"content",content)

            tempMediaRoot=getRootPath()
            updateResult=updateFile(tempMediaRoot, path, name,content)
            print("updateResult:", updateResult)
            if updateResult:
                return JsonResponse({"status":200, "message":"success", "data":{}})
            else:
                return JsonResponse({"status":400, "message":"error", "data":{}})
        else:
            return JsonResponse({"status":400, "message":"error", "data":{}})
    else:
        return render(request, 'mainLogin.html')
@login_required
def uploadFile(request):
    print("uploadFile")
    user_instance = user_check(request)
    if user_instance:
        
        if request.method == "POST":
            data=dict(request.POST.items())
            fileName=data["name"]
            filePath=data["path"]
            print("name:",data["name"]," path:",data["path"])
            
            
            
            print("request:",request)
            print("request.FILES:", request.FILES)
            print("request.POST:", request.POST)
            uploadFile=request.FILES.getlist('file')
            print("uploadFile:", uploadFile,len(uploadFile))
            #print("request.body:", request.body)
            #form_data = request.body
            #data = form_data.decode('utf-8')  # 将原始二进制数据解码成字符串
            #file=data.get('file')
            #dir=data.get('dir')
            #print("file:", file, "dir:", dir)
            # 指定文件保存的路径和文件名
            #file_path = getRootPath()

            #with open(os.path.join(file_path,'1.jpg'), 'wb') as f:
                # 将二进制数据写入文件
                #f.write(form_data)


            print("request.FILES.get('file'):",request.FILES.get('file'))
            #uploadFile = request.FILES.get('file')
            print("uploadFile:", uploadFile)
            returnData=[]
            if len(uploadFile)>0:
                for file in uploadFile:
                    print("file:", file.name)
                    newName,newPath=handle_uploaded_file(file,filePath)
                    print("newName:", newName, "newPath:", newPath)
                    getType=get_file_type(newName)['type']
                    returnData.append({"newName":newName,"newPath":newPath,"type":getType})
                print("returnData",returnData)
                #type=base.get_file_type(newName)['type']
                #{"newName":newName,"newPath":newPath,"type":type}
                return JsonResponse({"status":200,"message":"ok","data":returnData})
            else:
                return JsonResponse({"status":400, "message":"error", "data":{}})
        else:
            print("not files")
            return JsonResponse({"status":400, "message":"error", "data":{}})
    else:
        return render(request, 'mainLogin.html')
def handle_uploaded_file(uploaded_file,filePath):
    print("handle_uploaded_file")
     # 指定保存文件的目录
    tempMediaRoot=getRootPath()
    print("tempMediaRoot:",tempMediaRoot)
    if os.path.exists(os.path.join(tempMediaRoot,filePath))==False:
        os.makedirs(os.path.join(tempMediaRoot,filePath))
    
    fileName=checkPath(os.path.join(tempMediaRoot,filePath),uploaded_file.name,type="file")
    print("fileName:",fileName)
    temp_file_path = os.path.join(tempMediaRoot,filePath,fileName)
    print("temp_file_path:",temp_file_path)
    with open(temp_file_path, 'wb+') as destination:
        for chunk in uploaded_file.chunks():
            destination.write(chunk)
    return (fileName,os.path.join(filePath,fileName))

def getFileType(request,fileName):
    return JsonResponse({"status":200, "message":"ok", "data":get_file_type(fileName)})
